<?php

namespace app\index\controller;

use DateTime;
use DOMDocument;
use DOMXPath;
use think\Controller;
use think\Db;

class Gather extends Controller
{
    /**
     * 采集列表数据（工程建设、政府采购、其他交易【后续不抓】）
     * */
    public function gatherList()
    {
        $type_list = Db::name('gather_type')->where(['id' => ['IN', [2, 3, 4, 5, 6, 7, 8, 9, 11, 12]], 'api_url' => ['neq', '']])->select();
        foreach ($type_list as $v) {
            $res = $this->startGather($v['id'], $v['api_url']);
            echo "采集返回值：{$res}\n";
            if ($res == 'next') {
                continue;
            } elseif ($res == 'exit') {
                break;
            } else {
                break;
            }
        }
    }

    /**
     * 开始采集（工程建设、政府采购、其他交易【后续不抓】）
     * */
    public function startGather($id, $url, $current = 1, $size = 100)
    {
        $type_info = Db::name('gather_type')->field('pid,tenderProjectType')->where(['id' => $id])->find();

        $api_url = $url . '?current=' . $current . '&size=' . $size;

        if ($tenderProjectType = $type_info['tenderProjectType']) $api_url .= '&tenderProjectType=' . $tenderProjectType;

        $descs = 'noticeSendDate';
        if (in_array($id, [3, 4, 5, 6, 7, 8, 9, 11])) {
            $descs = 'noticeSendTime';
        } elseif ($id == 12) {
            $descs = 'noticeSendTime';
        } elseif ($id == 27) {
            $descs = 'releaseTime';
        }
        $api_url = $api_url . '&descs=' . $descs;

        echo "采集第 {$current} 页：{$api_url}\n";

        $data = file_get_contents($api_url);
        $data = json_decode($data, true);
        $list = $data['data']['records'];
        if ($list) {
            $pid = $type_info['pid'];
            if ($pid == 0) {
                $one_type_id = $id;
                $two_type_id = 0;
            } else {
                $one_type_id = $pid;
                $two_type_id = $id;
            }

            $region_name_field = 'regionName';
            $title_field = 'noticeTitle';
            $time_field = 'noticeSendDate';
            $link_id_field = 'bidSectionId';
            if (in_array($id, [3, 4, 5, 6, 7, 8, 9, 11])) {
                $region_name_field = 'name';
                $title_field = 'tenderProjectName';
                $time_field = 'noticeSendTime';
            } elseif ($id == 12) {
                $title_field = 'purchaseProjectName';
                $time_field = 'noticeSendTime';
            } elseif ($id == 27) {
                $title_field = 'title';
                $time_field = 'releaseTime';
                $link_id_field = 'id';
            }

            // 采集列表时间点（来自于宝塔任务计划设置的采集时间点）

            // 每天08:30,09:30,11:30,13:30,15:30,17:30,19:30,21:30,23:30执行
            $gather_date = ['08:30', '09:30', '11:30', '13:30', '15:30', '17:30', '19:30', '21:30', '23:30'];
            $gather_date_reverse = array_reverse($gather_date);
            // 找出当前时间最临近$gather_date的之前时间点；比如当前
            $now_date = '';
            foreach ($gather_date_reverse as $v) {
                if (date('Y-m-d ' . $v) <= date('Y-m-d H:i')) {
                    // 当前时间大于等于任务计划时间点
                    $now_date = $v;
                    break;
                }
            }
            $now_date_index = array_search($now_date, $gather_date);

            $prev_date = '';
            if ($now_date_index > 0) {
                $prev_date = $gather_date[$now_date_index - 1];
            }

            $data = [];
            foreach ($list as $v) {
                $int_time = strtotime($this->doTime($v[$time_field]));
                $gather_date = date('Y-m-d', $int_time);
                $gather_date_time = date('Y-m-d H:i', $int_time);

                if ($gather_date == date('Y-m-d')) {
                    if (!$prev_date || ($prev_date && date('Y-m-d ' . $prev_date) <= $gather_date_time)) {
                        $param = [
                            'link_id' => $v[$link_id_field],
                            'title' => isset($v[$title_field]) ? $v[$title_field] : '',
                            'one_type_id' => $one_type_id,
                            'two_type_id' => $two_type_id,
                            'content' => isset($v['noticeContent']) ? $this->doContent($v['noticeContent']) : '',
                            'regionCode' => $v['regionCode'],
                            'regionName' => $v[$region_name_field],
                            'noticeType' => isset($v['noticeType']) ? $v['noticeType'] : '',
                            'resourceState' => isset($v['resourceState']) ? $v['resourceState'] : '',
                            'from' => $v[$region_name_field] . '公共资源交易中心',
                            'publish_time' => isset($v[$time_field]) ? $this->doTime($v[$time_field]) : null
                        ];

                        $data[] = $param;
                    }
                }
            }

            if (empty($data)) {
                echo "该分类今日数据已采集完毕，开始采集下一个分类";
                return 'next';
            }

            Db::startTrans();
            try {
                $res = Db::name('gather')->insertAll($data);
                if ($res) {
                    Db::name('gather_type')->where(['id' => $id])->setField('page', $current);
                    Db::commit();
                    echo "成功插入第 {$current} 页，共插入：" . count($data) . " 条记录\n";
                    sleep(1);
                    return $this->startGather($id, $url, $current + 1, $size);
                } else {
                    Db::rollback();
                    return 'exit';
                }
            } catch (\Exception $e) {
                Db::rollback();
                return 'exit' . $e->getMessage();
            }
        } else {
            return 'next';
        }
    }

    /**
     * 采集列表数据（医药采购）
     * */
    public function gatherMedicineList()
    {
        $data = file_get_contents('https://www.hnsggzy.com/tradeApi/healingDrugs/query?current=1&size=1000&type=5');
        $data = json_decode($data, true);
        if ($data['code'] == 200) {
            $list = $data['data'];

            $data = [];
            foreach ($list as $v) {
                $data[] = [
                    'title' => $v['标题'],
                    'url' => 'https://yycg.hnsggzy.com' . str_replace('..' . '', $v['路径']),
                    'type' => $v['类型'],
                    'publish_time' => $v['时间'],
                ];
            }
            Db::name('gather_medicine')->insertAll($data);
        }
    }

    /**
     * 采集列表数据（国有资源）
     * */
    public function gatherResourceList()
    {
        $type_list = Db::name('gather_type')->where(['is_complete' => 0, 'pid' => 14, 'api_url' => ['neq', '']])->select();
        foreach ($type_list as $v) {
            $res = $this->startGatherResource($v['id'], $v['api_url'], $v['page'] + 1);
            echo "采集返回值：{$res}\n";
            if ($res == 'next') {
                continue;
            } elseif ($res == 'exit') {
                break;
            } else {
                break;
            }
        }
    }

    /**
     * 开始采集（国有资源）
     * */
    public function startGatherResource($id, $url, $current = 1, $size = 100)
    {
        $type_info = Db::name('gather_type')->field('pid')->where(['id' => $id])->find();

        $api_url = $url . '?current=' . $current . '&size=' . $size;

        $descs = 'pubSendTime';
        $time_field = 'pubSendTime';
        if ($id == 21) {
            $descs = 'listEndTime';
            $time_field = 'listEndTime';
        }
        $api_url = $api_url . '&descs=' . $descs;

        echo "采集第 {$current} 页：{$api_url}\n";

        $data = file_get_contents($api_url);
        $data = json_decode($data, true);
        $list = $data['data']['records'];
        if ($list) {
            $pid = $type_info['pid'];
            if ($pid == 0) {
                $one_type_id = $id;
                $two_type_id = 0;
            } else {
                $one_type_id = $pid;
                $two_type_id = $id;
            }

            $link_id_field = 'objectResourceId';
            if ($id == 18) $link_id_field = 'resourceId';

            $title_field = 'landName';
            if ($id == 16 || $id == 19 || $id == 21 || $id == 28) {
                $title_field = 'processNo';
            } elseif ($id == 18) {
                $title_field = 'aliasName';
            }

            $data = [];
            foreach ($list as &$v) {
                $projectName = '';
                if ($id == 15 || $id == 16) $projectName = $v['projectName'];

                $amountReceived_field = 'amountReceived';
                if (in_array($id, [17, 18, 19, 21])) {
                    $amountReceived_field = 'depositNeedPay';
                }

                $landLocation_field = 'landLocation';
                if ($id == 19) {
                    $landLocation_field = 'mineLocation';
                } elseif (in_array($id, [17, 18, 21])) {
                    $landLocation_field = '';
                }

                $data[] = [
                    'link_id' => isset($v[$link_id_field]) ? $v[$link_id_field] : '',
                    'landName' => isset($v[$title_field]) ? $v[$title_field] : '',
                    'projectName' => $projectName,
                    'resourceName' => $v['resourceName'],
                    'listStartTime' => $v['listStartTime'] ? $this->doTime($v['listStartTime']) : null,
                    'listEndTime' => $v['listEndTime'] ? $this->doTime($v['listEndTime']) : null,
                    'amountReceived' => $amountReceived_field && isset($v[$amountReceived_field]) ? $v[$amountReceived_field] : 0,
                    'initQuote' => $v['initQuote'],
                    'depositEndTime' => $v['depositEndTime'] ? $this->doTime($v['depositEndTime']) : null,
                    'landLocation' => $landLocation_field && isset($v[$landLocation_field]) ? $v[$landLocation_field] : '',
                    'highestQuote' => $v['highestQuote'] ? : '',
                    'processType' => $v['processType'] ? : '',
                    'processStage' => $v['processStage'] ? : '',
                    'processStatus' => $v['processStatus'] ? : '',
                    'resourceType' => $v['resourceType'] ? : '',
                    'one_type_id' => $one_type_id,
                    'two_type_id' => $two_type_id,
                    'regionCode' => $v['regionCode'],
                    'regionName' => $v['name'],
                    'publish_time' => isset($v[$time_field]) ? $this->doTime($v[$time_field]) : null
                ];
            }

            Db::startTrans();
            try {
                $res = Db::name('gather_resource')->insertAll($data);
                if ($res) {
                    Db::name('gather_type')->where(['id' => $id])->setField('page', $current);
                    Db::commit();
                    echo "成功插入第 {$current} 页，共插入：" . count($data) . " 条记录\n";
                    sleep(1);
                    return $this->startGatherResource($id, $url, $current + 1, $size);
                } else {
                    Db::rollback();
                    return 'exit';
                }
            } catch (\Exception $e) {
                Db::rollback();
                return 'exit' . $e->getMessage();
            }
        } else {
            Db::name('gather_type')->where(['id' => $id])->setField('is_complete', 1);
            return 'next';
        }
    }

    /**
     * 采集列表数据（国有资产）
     * */
    public function gatherPropertyList()
    {
        $info = Db::name('gather_type')->where(['is_complete' => 0, 'id' => 22])->find();
        $this->startGatherProperty($info['id'], $info['api_url'], $info['page'] + 1);
        echo "采集完成";
    }

    /**
     * 开始采集（国有资产）
     * */
    public function startGatherProperty($id, $url, $current = 1, $size = 100)
    {
        $api_url = $url . '?current=' . $current . '&size=' . $size . '&ascs=pubSendTime';

        echo "采集第 {$current} 页：{$api_url}\n";

        $data = file_get_contents($api_url);
        $data = json_decode($data, true);
        $list = $data['data']['records'];
        if ($list) {
            $data = [];
            foreach ($list as &$v) {
                $data[] = [
                    'link_id' => $v['resourceId'],
                    'markName' => $v['markName'],
                    'processNo' => $v['processNo'],
                    'applyStartTime' => $v['applyStartTime'] ? $this->doTime($v['applyStartTime']) : null,
                    'applyEndTime' => $v['applyEndTime'] ? $this->doTime($v['applyEndTime']) : null,
                    'depositNeedPay' => $v['depositNeedPay'] ? : 0,
                    'initQuote' => $v['initQuote'] ? : 0,
                    'picture' => $v['picture'] ? : '',
                    'processType' => $v['processType'] ? : '',
                    'one_type_id' => $id,
                    'two_type_id' => 0,
                    'regionCode' => $v['regionCode'],
                    'regionName' => $v['name'],
                ];
            }

            Db::startTrans();
            try {
                $res = Db::name('gather_property')->insertAll($data);
                if ($res) {
                    Db::name('gather_type')->where(['id' => $id])->setField('page', $current);
                    Db::commit();
                    echo "成功插入第 {$current} 页，共插入：" . count($data) . " 条记录\n";
                    sleep(1);
                    return $this->startGatherProperty($id, $url, $current + 1, $size);
                } else {
                    Db::rollback();
                    return 'exit';
                }
            } catch (\Exception $e) {
                Db::rollback();
                return 'error：' . $e->getMessage();
            }
        } else {
            Db::name('gather_type')->where(['id' => $id])->setField('is_complete', 1);
            return 'complete';
        }
    }

    /**
     * 采集列表数据（环境权-排污权）
     * */
    public function gatherEnvironmentList()
    {
        $info = Db::name('gather_type')->where(['is_complete' => 0, 'id' => 24])->find();
        $this->startGatherEnvironment($info['id'], $info['api_url'], $info['page'] + 1);
        echo "采集完成";
    }

    /**
     * 开始采集（环境权-排污权）
     * */
    public function startGatherEnvironment($id, $url, $current = 1, $size = 100)
    {
        $api_url = $url . '?current=' . $current . '&size=' . $size . '&ascs=pubSendTime';

        echo "采集环境权第 {$current} 页：{$api_url}\n";

        $data = file_get_contents($api_url);
        $data = json_decode($data, true);
        $list = $data['data']['records'];
        if ($list) {
            $data = [];
            foreach ($list as &$v) {
                if ($v['processType'] == 'AGREEMENT_TRANSFER') {
                    $start_time_field = 'dealStartTime';
                    $end_time_field = 'dealEndTime';
                } else {
                    $start_time_field = 'listStartTime';
                    $end_time_field = 'listEndTime';
                }

                $data[] = [
                    'link_id' => $v['resourceId'],
                    'processNo' => $v['processNo'],
                    'listStartTime' => $v[$start_time_field] ? $this->doTime($v[$start_time_field]) : null,
                    'listEndTime' => $v[$end_time_field] ? $this->doTime($v[$end_time_field]) : null,
                    'initQuote' => $v['initQuote'] ? : 0,
                    'quoteRange' => $v['quoteRange'] ? : 0,
                    'quoteUnit' => $v['quoteUnit'] ? : '',
                    'quoteUnitName' => $v['quoteUnitName'] ? : '',
                    'topQuoteNum' => $v['topQuoteNum'] ? : '',
                    'transferorName' => $v['transferorName'] ? : '',
                    'ownMainName' => $v['ownMainName'] ? : '',
                    'processType' => $v['processType'] ? : '',
                    'processCategory' => $v['processCategory'] ? : '',
                    'one_type_id' => 23,
                    'two_type_id' => $id,
                    'regionCode' => $v['regionCode'],
                    'regionName' => $v['regionName'],
                ];
            }

            Db::startTrans();
            try {
                $res = Db::name('gather_environment')->insertAll($data);
                if ($res) {
                    Db::name('gather_type')->where(['id' => $id])->setField('page', $current);
                    Db::commit();
                    echo "成功插入第 {$current} 页，共插入：" . count($data) . " 条记录\n";
                    sleep(1);
                    return $this->startGatherEnvironment($id, $url, $current + 1, $size);
                } else {
                    Db::rollback();
                    return 'exit';
                }
            } catch (\Exception $e) {
                Db::rollback();
                return 'error：' . $e->getMessage();
            }
        } else {
            Db::name('gather_type')->where(['id' => $id])->setField('is_complete', 1);
            return 'complete';
        }
    }

    /**
     * 将招标计划的content字段解析成数组并保存到content_json字段
     * */
    public function runGatherContentJson()
    {
        $list = Db::name('gather')->where(['two_type_id' => 2, 'is_gather' => ['neq', 1]])->select();
        $count = 0;
        foreach ($list as $val) {
            if ($val['content']) {
                $content = parseHtmlTableToArray($val['content']);
                $content = json_encode($content, JSON_UNESCAPED_UNICODE);
                $data = [
                    'content_json' => $content,
                    'is_gather' => 1
                ];
                Db::name('gather')->where('id', $val['id'])->update($data);
                $count++;
            }
        }
        echo date('Y-m-d H:i:s') . ' 解析保存完成，本次受影响数量：' . $count;
    }

    /**
     * 生成待抓取的详情url
     * */
    public function createWaitGatherFile()
    {
        $where['is_gather'] = 0;
        $where['one_type_id'] = ['neq', 27];
        //        $where['two_type_id'] = ['neq', 2];
        $list = Db::name('gather')->field('id,one_type_id,two_type_id,link_id')->where($where)->order('publish_time desc')->limit(80000)->select();
        if ($list) {
            $data = [];
            foreach ($list as &$v) {
                switch ($v['two_type_id']) {
                    case 3:
                        $api_name = 'construction';
                        break;
                    case 4:
                        $api_name = 'transporatation';
                        break;
                    case 5:
                        $api_name = 'waterConservancy';
                        break;
                    case 6:
                        $api_name = 'industry';
                        break;
                    case 7:
                        $api_name = 'agencyConstruction';
                        break;
                    case 8:
                        $api_name = 'agriculturalProject';
                        break;
                    case 9:
                        $api_name = 'environmentalProject';
                        break;
                    case 11:
                        $api_name = 'other';
                        break;
                }
                if ($v['link_id']) {
                    if ($v['one_type_id'] == 12) {
                        // 政府采购
                        $url = 'https://www.hnsggzy.com/#/resources/projectDetail/governmentPurchase?bidSectionId=' . $v['link_id'] . '&t=ZFCG';
                    } else {
                        // 工程建设
                        $url = 'https://www.hnsggzy.com/#/resources/transactionDetail/' . $api_name . '?bidSectionId=' . $v['link_id'] . '&t=GC';
                    }

                    $data[] = [
                        'id' => $v['id'],
                        'url' => $url,
                        'is_gather' => 0
                    ];
                }
            }
            file_put_contents(RUNTIME_PATH . 'wait_gather.json', json_encode($data, JSON_UNESCAPED_UNICODE));

            echo 'wait_gather.json文件已生成';
        }
    }

    /**
     * 生成今日待抓取的详情url
     * */
    public function createTodayWaitGatherFile()
    {
        $where['is_gather'] = ['IN', [0, 2]];                       // != 1
        $where['one_type_id'] = ['IN', [1]];                    // != 27
        $where['two_type_id'] = ['IN', [3, 4, 5, 6, 7, 8, 9, 11]];  // != 2
//        $where['publish_time'] = ['egt', date('Y-m-d 00:00:00')];
        $where['publish_time'] = ['egt', '2025-11-15 00:00:00'];


//        $list = Db::name('gather')->field('id,one_type_id,two_type_id,link_id')->where($where)->order('publish_time desc')->select();
        $list = Db::name('gather')->field('id,one_type_id,two_type_id,link_id')->where($where)->order('publish_time desc')->limit(300)->select();

        if ($list) {
            $data = [];
            foreach ($list as &$v) {
                switch ($v['two_type_id']) {
                    case 3:
                        $api_name = 'construction';
                        break;
                    case 4:
                        $api_name = 'transporatation';
                        break;
                    case 5:
                        $api_name = 'waterConservancy';
                        break;
                    case 6:
                        $api_name = 'industry';
                        break;
                    case 7:
                        $api_name = 'agencyConstruction';
                        break;
                    case 8:
                        $api_name = 'agriculturalProject';
                        break;
                    case 9:
                        $api_name = 'environmentalProject';
                        break;
                    case 11:
                        $api_name = 'other';
                        break;
                }
                if ($v['link_id']) {
                    if ($v['one_type_id'] == 12) {
                        // 政府采购
                        $url = 'https://www.hnsggzy.com/#/resources/projectDetail/governmentPurchase?bidSectionId=' . $v['link_id'] . '&t=ZFCG';
                    } else {
                        // 工程建设
                        $url = 'https://www.hnsggzy.com/#/resources/transactionDetail/' . $api_name . '?bidSectionId=' . $v['link_id'] . '&t=GC';
                    }
                    $data[] = [
                        'id' => $v['id'],
                        'url' => $url,
                        'is_gather' => 0
                    ];
                }
            }
            file_put_contents(RUNTIME_PATH . 'today_wait_gather.json', json_encode($data, JSON_UNESCAPED_UNICODE));

            echo 'today_wait_gather.json文件已生成';
        }
    }

    /**
     * 修改 content 和 content_json 字段
     * */
    public function insertContent()
    {
        $files = $this->readFile('gather_html');
        if ($files) {
            foreach ($files as $v) {
                $content = file_get_contents($v);
                $content_json = $this->getContentJson($content);
                $id = str_replace([RUNTIME_PATH . 'gather_html/', '.txt'], '', $v);
                if ($content && $content_json && $id) {
                    // 成功
                    $data = [
                        'content' => $content,
                        'content_json' => $content_json,
                        'is_gather' => 1
                    ];
                    $res = Db::name('gather')->where('id', $id)->update($data);
                    if ($res) {
                        unlink($v);
                    } else {
                        // 失败
                        Db::name('gather')->where('id', $id)->setField('is_gather', 2);
                    }

                } else {
                    // 失败
                    Db::name('gather')->where('id', $id)->setField('is_gather', 2);
                }
            }
        }

        return true;
    }

    /**
     * 生成待抓取的详情url（其他交易）
     * */
    public function createWaitGatherFileOther()
    {
        $where['is_gather'] = 0;
        $where['one_type_id'] = 27;

        $list = Db::name('gather')->field('id,link_id,regionCode')->where($where)->order('publish_time desc')->select();
        if ($list) {
            $data = [];
            foreach ($list as &$v) {
                $url = 'https://www.hnsggzy.com/#/resources/projectDetail/otherTrade?id=' . $v['link_id'] . '&regionCode=' . $v['regionCode'];
                $data[] = [
                    'id' => $v['id'],
                    'url' => $url,
                    'is_gather' => 0
                ];
            }
            file_put_contents(RUNTIME_PATH . 'wait_gather_other.json', json_encode($data, JSON_UNESCAPED_UNICODE));
        }
        echo 'wait_gather_other.json文件已生成';
    }

    /**
     * 修改content字段（其他交易）
     * */
    public function insertContentOther()
    {
        $files = $this->readFile('gather_other_html');
        if ($files) {
            foreach ($files as $v) {
                $content = file_get_contents($v);
                $id = str_replace([RUNTIME_PATH . 'gather_other_html/', '.txt'], '', $v);
                if ($content && $id) {
                    // 成功
                    $data = [
                        'content' => formatRichTextForWechatMiniProgram($content),
                        'is_gather' => 1
                    ];
                    $res = Db::name('gather')->where('id', $id)->update($data);
                    if ($res) {
                        unlink($v);
                    } else {
                        // 失败
                        Db::name('gather')->where('id', $id)->setField('is_gather', 2);
                    }
                } else {
                    // 失败
                    Db::name('gather')->where('id', $id)->setField('is_gather', 2);
                }
            }
        }

        return true;
    }

    public function readFile($html_dir)
    {
        $dir = RUNTIME_PATH . $html_dir;
        $files = [];

        foreach (scandir($dir) as $file) {
            if ($file === '.' || $file === '..') continue;

            $fullPath = $dir . DIRECTORY_SEPARATOR . $file;
            if (is_file($fullPath)) {
                $files[] = $fullPath;
            }
        }
        return $files;
    }

    public function getContentJson($html)
    {
        libxml_use_internal_errors(true);
        $dom = new DOMDocument();
        $dom->loadHTML('<?xml encoding="utf-8" ?>' . $html); // 避免乱码
        $xpath = new DOMXPath($dom);

        // 获取标题和表格
        $titles = $xpath->query('//div[@class="table-title"]');

        $result = [];

        $titleCount = $titles->length;

        for ($i = 0; $i < $titleCount; $i++) {
            $title = $titles->item($i)->nodeValue;
            $data = [];

            $titleNode = $titles->item($i);

            // 找到离标题最近的下一个 table 元素
            $nextTable = null;
            $sibling = $titleNode->nextSibling;
            while ($sibling) {
                if ($sibling->nodeType === XML_ELEMENT_NODE && $sibling->nodeName === 'table') {
                    $nextTable = $sibling;
                    break;
                }
                $sibling = $sibling->nextSibling;
            }

            // 解析当前标题对应的 table 数据
            if ($nextTable) {
                $rows = $xpath->query('.//tr', $nextTable);
                foreach ($rows as $row) {
                    $ths = $xpath->query('./th', $row);
                    $tds = $xpath->query('./td', $row);
                    $count = min($ths->length, $tds->length);
                    for ($j = 0; $j < $count; $j++) {
                        $label = trim($ths->item($j)->nodeValue);
                        $value = trim($tds->item($j)->nodeValue);
                        if ($label !== '') {
                            $data[$label] = $value;
                        }
                    }
                }
            }

            // 如果是最后一个标题，额外提取“详情内容”
            if ($i == $titleCount - 1) {
                $form = $xpath->query('//form[contains(@class,"table-content")]')->item(0);
                if ($form) {
                    // 获取 form 内所有的 <div>（跳过 table 外的详情内容）
                    $divs = $xpath->query('.//div', $form);
                    foreach ($divs as $div) {
                        if ($div->getElementsByTagName('table')->length === 0) {
                            $detailText = trim($div->nodeValue);
                            if ($detailText !== '') {
                                $data['详情'] = $detailText;
                                break; // 提取第一个有效详情内容即可
                            }
                        }
                    }
                }
            }

            $result[] = [
                'name' => $title,
                'data' => $data
            ];
        }

        header('Content-Type: application/json');
        return json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    }


    public function doContent($html)
    {
        // 1. 替换特殊字符
        $html = str_replace(["\t", '\"'], ['', '"'], $html);
        // 2. 正则提取 <body> 标签中的内容
        if (preg_match('/<body[^>]*>(.*?)<\/body>/is', $html, $matches)) {
            return trim($matches[1]); // 返回 body 内部内容
        }
        // 如果没有匹配到 body，直接返回清洗后的原文
        return trim($html);
    }

    public function doTime($datetime)
    {
        try {
            // 创建 DateTime 对象，自动识别时区
            $dt = new DateTime($datetime);
            // 按照目标格式返回
            return $dt->format('Y-m-d H:i:s');
        } catch (\Exception $e) {
            // 如果格式错误，返回空字符串或原始数据（你可根据实际需求修改）
            return null;
        }
    }
}